class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ret;
        int row = matrix.size(), col = matrix[0].size();
        int top = 0, bottom = row - 1, left = 0, right = col - 1;

        while (1)
        {
            for (int i = left; i <= right; i++)
                ret.push_back(matrix[top][i]);
            
            top++;
            if (left > right || top > bottom)
                break;   
            for (int i = top; i <= bottom; i++)
                ret.push_back(matrix[i][right]);
            
            right--;
            if (left > right || top > bottom)
                break;   
            for (int i = right; i >= left; i--)
                ret.push_back(matrix[bottom][i]);
            
            bottom--;
            if (left > right || top > bottom)
                break;   
            for (int i = bottom; i >= top; i--)
                ret.push_back(matrix[i][left]);

            left++;
            if (left > right || top > bottom)
                break;   
        }

        return ret;
    }
};